<template>
  <div>
    <wise-crud ref="wise-crud" :urls="urls" :fields="fields" :handle="[]" :filters="filters">
      <template slot="outHandle">
        <el-col :span="3">
          <el-button type="primary" @click="handleAdd">
            <i class="el-icon-plus" />
            上传资料
          </el-button>
        </el-col>
      </template>
      <template v-slot:handle="slotProps">
        <el-button type="info" size="small" class="activeBtn" round @click.native.prevent="viewHandle(slotProps.row)">查看</el-button>
        <el-button type="info" size="small" class="activeBtn" round @click.native.prevent="download(slotProps.row)">下载</el-button>
        <el-button
          v-permission="['superSysOpsAdmin', 'entAdmin']"
          type="danger"
          size="small"
          round
          @click.native.prevent="removeHandle(slotProps.row)"
        >
          删除
        </el-button>
      </template>
    </wise-crud>

    <el-dialog ref="dialog" title="上传资料" :visible.sync="dialog" destroy-on-close>
      <div v-if="dialog" class="draw-body">
        <div class="wise-form">
          <el-form ref="ruleForm" :model="object" :rules="rules" :validate-on-rule-change="false" label-width="130px" label-suffix=":">
            <el-form-item label="附件名称" prop="depict">
              <el-input v-model="object.depict" placeholder="请输入附件名称" clearable autofocus />
            </el-form-item>
            <el-form-item label="附件上传" prop="fileUrl">
              <wise-file v-model="object.fileUrl" :limit="1" upload-type="file" />
            </el-form-item>
            <el-row type="flex" justify="end">
              <el-button @click="resetForm('ruleForm')">重置</el-button>
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-dialog>

    <el-dialog ref="viewDialog" title="查看" :visible.sync="viewDialog" destroy-on-close>
      <div v-if="viewDialog" class="draw-body">
        <div class="wise-form">
          <el-form ref="ruleForm" :model="object" :validate-on-rule-change="false" label-width="130px" label-suffix=":">
            <el-form-item label="附件名称" prop="depict">
              <span>{{ object.depict }}</span>
            </el-form-item>
            <el-form-item v-if="object.fileUrl" label="附件上传" prop="fileUrl">
              <!-- <el-image
                v-for="(img, i) in object.fileUrl.split(';')"
                :key="i"
                class="image"
                fit="cover"
                alt="点击查看大图"
                :src="img | imgPath"
                :preview-src-list="getSrcList(object.fileUrl)"
              /> -->
              <file-type :files="object.fileUrl" />
            </el-form-item>
            <el-row type="flex" justify="end">
              <el-button @click="viewDialog = false">取 消</el-button>
              <el-button type="primary" @click="viewDialog = false">关 闭</el-button>
            </el-row>
          </el-form>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { imgPath } from '@/filters'
import WiseCrud from '@/components/Crud/wiseCrud'
import { postHandle } from '../../../../../api'
import WiseFile from '@/components/Crud/components/wiseFile'
import { downloadHandle } from '@/api'
import FileType from '@/components/Crud/components/fileType'
export default {
  components: { WiseCrud, WiseFile, FileType },
  props: {
    type: {
      type: Number,
      required: true
    }
  },
  data() {
    return {
      urls: {
        list: '/api/v1/welder-sbtx-second/archive-comb/list'
      },
      fields: [
        { label: '序号', type: 'index', use: ['table'] },
        {
          label: '项目名称',
          prop: 'projectInfo.name',
          type: 'text',
          use: ['table']
        },
        {
          label: '附件名称',
          prop: 'depict',
          type: 'text',
          use: ['table']
        },
        { label: '操作', type: 'handle', use: ['table'], handle: [], tableWidth: 220 }
      ],
      object: {
        depict: null,
        fileUrl: null
      },
      rules: {
        depict: [{ required: true, message: '必填项不能为空', trigger: 'blur' }],
        fileUrl: [{ required: true, message: '必填项不能为空', trigger: 'blur' }]
      },
      viewDialog: false,
      dialog: false
    }
  },
  computed: {
    spaceId() {
      return this.$store.getters.spaceId
    },
    filters() {
      return [
        {
          field: 'spaceId',
          operator: 'EQUALS',
          value: this.spaceId
        },
        {
          field: 'type',
          operator: 'EQUALS',
          value: this.type
        }
      ]
    }
  },
  methods: {
    handleAdd() {
      this.object = {
        depict: null,
        fileUrl: null
      }
      this.dialog = true
    },
    getSrcList(str) {
      let arr = []
      if (str) {
        arr = str.split(';')
      }
      return arr.map(item => imgPath(item))
    },
    getShowData(id) {
      postHandle(`/api/v1/welder-sbtx-second/archive-comb/show/${id}`).then(res => {
        this.object = res.result
      })
    },
    // 重置
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    // 提交
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let params = {
            obj: {
              spaceId: this.spaceId,
              type: this.type,
              depict: this.object.depict,
              fileUrl: this.object.fileUrl
            }
          }
          postHandle(`/api/v1/welder-sbtx-second/archive/create`, params).then(res => {
            this.$message.success('成功')
            this.dialog = false
            this.$refs['wise-crud'].handleSearch(0)
          })
        } else {
          return false
        }
      })
    },
    viewHandle({ id }) {
      this.getShowData(id)
      this.viewDialog = true
    },
    removeHandle({ id }) {
      this.$confirm('您确定要删除该项目, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          postHandle(`/api/v1/welder-sbtx-second/archive/remove/${id}`).then(response => {
            this.$message('删除成功')
            this.$refs['wise-crud'].handleSearch(0)
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          })
        })
    },
    download({ fileUrl }) {
      downloadHandle(process.env.VUE_APP_DOWNLOAD_URL, {
        obj: {
          url: process.env.VUE_APP_BASE_URL + process.env.VUE_APP_FILE_PATH + fileUrl
        }
      }).then(res => {
        let disposition = res.headers['content-disposition'].replace(/\"/g, '').split('=')
        let fileName = decodeURI(disposition[disposition.length - 1])
        let blob = new Blob([res.data], { type: res.data.type })
        let downloadElement = document.createElement('a')
        let href = window.URL.createObjectURL(blob) // 创建下载的链接
        downloadElement.href = href
        downloadElement.download = fileName // 下载后文件名
        document.body.appendChild(downloadElement)
        downloadElement.click() // 点击下载
        document.body.removeChild(downloadElement) // 下载完成移除元素
        window.URL.revokeObjectURL(href) // 释放blob对象
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.image {
  width: 150px;
  height: 150px;
  margin-right: 10px;
}
</style>
